/*
 *所有关于mes_virtualrfiddata2类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*mes_virtualrfiddata2Service对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using HslCommunication;
using HslCommunication.Profinet.Siemens;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using System.Linq;
using System.Linq.Expressions;
using VolPro.Core.BaseProvider;
using VolPro.Core.Enums;
using VolPro.Core.Extensions;
using VolPro.Core.Extensions.AutofacManager;
using VolPro.Core.ManageUser;
using VolPro.Core.Services;
using VolPro.Core.Utilities;
using VolPro.Entity.DomainModels;
using VolPro.MES.IRepositories;

namespace VolPro.MES.Services
{
    public partial class mes_virtualrfiddata2Service
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly Imes_virtualrfiddata2Repository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public mes_virtualrfiddata2Service(
            Imes_virtualrfiddata2Repository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }

        WebResponseContent webResponse = new WebResponseContent();
        /// <summary>
        /// 读库写TAG
        /// </summary>
        /// <returns></returns>
        public async Task<WebResponseContent> MES_TAGFormSQL(string sN, string opName) 
        {
            try
            {
                bool task1 = TagFormSQL(sN, opName);//读库写plc
                //Task<MES_ProductionPlanDetail> task2 = GetUpDetail(sN); //查上线记录 返回机型 订货号 托盘号（这样plcTag不能使用时，也能保证客户端的装机信息上传的最低要求）
                MES_ProductionPlanDetail task2 = GetUpDetail(sN);
                //var timeoutTask = Task.Delay(TimeSpan.FromSeconds(5000)); // 创建超时Task
                                                                          //var allTasksTask = Task.WhenAll(task1, task2);

                // 等待任意一个先完成（任务组或超时）
                //var completedTask = await Task.WhenAny(allTasksTask, timeoutTask);

                //if (completedTask == timeoutTask)
                //{
                //    //Console.WriteLine("操作超时！");
                //    //// 可以选择取消任务（如果有CancellationToken）
                //    //return;
                //    webResponse.Code = "500";
                //    webResponse.Error("超时失败");
                //}
                //else
                //{
                    if (task2 == null)
                    {
                        webResponse.Code = "300";
                        webResponse.Error("无上线记录");
                    }
                    else
                    {
                        // 正常获取结果
                        bool result1 = task1;
                        MES_ProductionPlanDetail result2 = task2;
                        webResponse.Code = "200";
                        webResponse.OK("成功", new { MaterialSpecification = result2.MaterialSpecification, PlanDetailID = result2.PlanDetailID, OrderID = result2.OrderID, PlanQuantity = result2 .PlanDetailID, BomId =result2.BomId});
                    }
                //}
            }
            catch (Exception ex)
            {
                webResponse.Code = "500";
                webResponse.Error(ex.Message);
            }
            finally
            {
                //    if (!string.IsNullOrEmpty(responseContent.Code))
                //    {
                //        //memoryCache.Remove(loginInfo.UUID);
                //    }
                Logger.Info(LoggerType.Login, webResponse.Message, $"", null);
            }
            return webResponse;
        }
        /// <summary>
        /// 读TAG写库
        /// </summary>
        /// <returns></returns>
        public async Task<WebResponseContent> MES_TAGToSQL(string sN, string opName)
        {
            var s = await TagToSQL(sN, opName);
            if (string.IsNullOrEmpty(s))
            {
                webResponse.Code = "200";
                webResponse.OK("成功");
            }
            else
            {
                webResponse.Code = "500";
                webResponse.Error(s);
            }
            return webResponse;
            /*
            SiemensS7Net siemensS7Net = null;
            string message = string.Empty;
            bool isSuccess = false;
            MES_VirtualRFIDSet tagSet = null;
            OperateResult<Byte[]> s7r = null;
            try
            {
                //var userName = UserContext.Current.UserName;
                //var opName = GetOP(userName);
               
                ///////////获取此工位的虚拟TAG地址配置////////////////////////////
                tagSet = await _repository.DbContext.Set<MES_VirtualRFIDSet>()
                   .FirstOrDefaultAsync(b => b.OPName == opName);

                /////////////////////S7批量读取PLC X个db
                siemensS7Net = new SiemensS7Net(SiemensPLCS.S1200)
                {
                    IpAddress = tagSet.PlcIp,
                    Port = tagSet.PlcPort
                };

                var d = siemensS7Net.ConnectServer();

                if (d.IsSuccess)
                {
                    message = "PLC连接失败";
                }

                s7r = siemensS7Net.Read(tagSet.DB, (ushort)tagSet.Length);
                isSuccess = s7r.IsSuccess;

                if (!isSuccess)
                {
                    message = s7r.Message ?? "PLC读取操作失败";
                }

                var tagData = await _repository.DbContext.Set<MES_VirtualRFIDData>()//
   .Where(b => b.SerialNumber == sN)
   .OrderByDescending(b => b.CreateDate)
   .FirstOrDefaultAsync();

                if (tagData == null)//之前没有这条记录就新增加一条
                {
                    MES_VirtualRFIDData mES_VirtualRFIDData = new MES_VirtualRFIDData();
                    mES_VirtualRFIDData.Creator = opName;
                    mES_VirtualRFIDData.CreateDate = DateTime.Now;
                    mES_VirtualRFIDData.VirtualSetID = tagSet.ID;
                    mES_VirtualRFIDData.OPName = opName;
                    mES_VirtualRFIDData.SerialNumber = sN;
                    mES_VirtualRFIDData.ProcessCode = string.Empty;
                    mES_VirtualRFIDData.RFID = s7r.Content;
                    mES_VirtualRFIDData.Description = string.Empty;
                    //mES_VirtualRFIDData.Enable = 1;
                    // 添加到上下文
                    _repository.DbContext.Set<MES_VirtualRFIDData>().Add(mES_VirtualRFIDData);
                    // 或者使用以下方式（如果DbSet属性已定义）：
                    // _repository.DbContext.MES_VirtualRFIDData.Add(mES_VirtualRFIDData);

                    // 保存到数据库
                    int result = _repository.DbContext.SaveChanges();

                    if (result > 0)
                    {
                        message = "保存成功！";
                    }
                    else
                    {
                        message = "没有保存任何数据。";
                    }
                    return webResponse;
                }
                else
                { //之前有记录就更新


                }
            }
            catch (Exception)
            {
            }
            finally
            {
                // 记录日志
                string dbInfo = listA?.DB?.ToString() ?? "未知DB";
                string successStatus = s7r?.IsSuccess.ToString() ?? "未知状态";

                Logger.Info(LoggerType.Login,
                           $"写plcDB1000:db {dbInfo}-> {successStatus} {message}",
                           $"UserName:{UserContext.Current.UserName}",
                           null);
                //siemensS7Net.();//断开连接
                // 释放资源
                siemensS7Net = null;
            }
            */
        }
        private async Task<string> TagToSQL(string sN, string opName)
        {
            SiemensS7Net siemensS7Net = null;
            string message = string.Empty;
            bool isSuccess = false;
            mes_virtualrfidset2 tagSet = null;
            OperateResult<Byte[]> s7r = null;
            try
            {
                //var userName = UserContext.Current.UserName;
                //var opName = GetOP(userName);

                ///////////获取此工位的虚拟TAG地址配置////////////////////////////
                tagSet = await _repository.DbContext.Set<mes_virtualrfidset2>()
                   .FirstOrDefaultAsync(b => b.OPName == opName);

                /////////////////////S7批量读取PLC X个db
                siemensS7Net = new SiemensS7Net(SiemensPLCS.S1200)
                {
                    IpAddress = tagSet.PlcIp,
                    Port = tagSet.PlcPort
                };

                var d = siemensS7Net.ConnectServer();

                if (d.IsSuccess)
                {
                    //message = "PLC连接失败";
                }

                s7r = siemensS7Net.Read(tagSet.DB, (ushort)tagSet.Length);
                isSuccess = s7r.IsSuccess;

                if (!isSuccess)
                {
                    return message = s7r.Message ?? "PLC读取操作失败";
                }

                var tagData = await _repository.DbContext.Set<MES_VirtualRFIDData>()//
   .Where(b => b.SerialNumber == sN)
   .OrderByDescending(b => b.CreateDate)
   .FirstOrDefaultAsync();

                if (tagData == null)//之前没有这条记录就新增加一条
                {
                    MES_VirtualRFIDData mES_VirtualRFIDData = new MES_VirtualRFIDData();
                    mES_VirtualRFIDData.Creator = opName;
                    mES_VirtualRFIDData.CreateDate = DateTime.Now;
                    mES_VirtualRFIDData.VirtualSetID = tagSet.ID;
                    mES_VirtualRFIDData.OPName = opName;
                    mES_VirtualRFIDData.SerialNumber = sN;
                    mES_VirtualRFIDData.ProcessCode = string.Empty;
                    mES_VirtualRFIDData.RFID = s7r.Content;
                    mES_VirtualRFIDData.Description = string.Empty;
                    //mES_VirtualRFIDData.Enable = 1;
                    // 添加到上下文
                    _repository.DbContext.Set<MES_VirtualRFIDData>().Add(mES_VirtualRFIDData);
                    // 或者使用以下方式（如果DbSet属性已定义）：
                    // _repository.DbContext.MES_VirtualRFIDData.Add(mES_VirtualRFIDData);

                    // 保存到数据库
                    int result = _repository.DbContext.SaveChanges();

                    if (result > 0)
                    {
                    }
                    else
                    {
                        message = "没有保存任何数据。";
                    }
                }
                else
                { //之前有记录就更新

                    // 附加实体
                    _repository.DbContext.Set<MES_VirtualRFIDData>().Attach(tagData);

                    // 只更新特定字段
                    _repository.DbContext.Entry(tagData).Property(u => u.RFID).IsModified = true;
                    _repository.DbContext.Entry(tagData).Property(u => u.Modifier).IsModified = true;
                    _repository.DbContext.Entry(tagData).Property(u => u.ModifyDate).IsModified = true;
                    tagData.RFID = s7r.Content;
                    tagData.Modifier = opName;
                    tagData.ModifyDate = DateTime.Now;
                    int result = _repository.DbContext.SaveChanges();
                    if (result > 0)
                    {
                    }
                    else
                    {
                        message = "没有保存任何数据。";
                    }
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            finally
            {
                Logger.Info(LoggerType.Login, $"写plcDB1000:db {tagSet?.PlcIp}-> {""} {message}",
                           $"UserName:{UserContext.Current.UserName}", null);
                //siemensS7Net.();//断开连接
                // 释放资源
                siemensS7Net = null;
            }

            return message;

            ////////        SiemensS7Net siemensS7Net = null;
            ////////        string message = string.Empty;
            ////////        bool isSuccess = false;
            ////////        MES_VirtualRFIDSet listA = null;
            ////////        OperateResult<Byte[]> s7r = null;
            ////////        try
            ////////        {
            ////////            var opname = GetOP(sN);
            ////////            var listB = await _repository.DbContext.Set<MES_VirtualRFIDData>()//
            ////////.Where(b => b.SerialNumber == sN)
            ////////.OrderByDescending(b => b.CreateDate)
            ////////.FirstOrDefaultAsync();

            ////////            if (listB == null)
            ////////            {
            ////////                message = $"未找到SerialNumber为{sN}的MES_VirtualRFIDData记录";
            ////////                webResponse.Error(message);
            ////////                return false;
            ////////            }
            ////////            listA = await _repository.DbContext.Set<MES_VirtualRFIDSet>()
            ////////               .FirstOrDefaultAsync(b => b.OPName == opname);
            ////////            siemensS7Net = new SiemensS7Net(SiemensPLCS.S1200)
            ////////            {
            ////////                IpAddress = listA.PlcIp,
            ////////                Port = listA.PlcPort
            ////////            };

            ////////            var d = siemensS7Net.ConnectServer();

            ////////            if (d.IsSuccess)
            ////////            {
            ////////                message = "PLC连接失败";
            ////////                return false;
            ////////            }

            ////////            s7r = siemensS7Net.Read(listA.DB, (ushort)listB.Length);
            ////////            isSuccess = s7r.IsSuccess;

            ////////            if (!isSuccess)
            ////////            {
            ////////                message = s7r.Message ?? "PLC读取操作失败";
            ////////                return false;
            ////////            }
            ////////            ese   
            ////////            {
            ////////                listB.
            ////////                int affectedRows = _repository.DbContext.Set<MES_VirtualRFIDSet>().SaveChanges();
            ////////            }
            ////////        }
            ////////        catch (Exception)
            ////////        {
            ////////            return false;
            ////////        }
            ////////        finally
            ////////        {
            ////////            // 记录日志
            ////////            string dbInfo = listA?.DB?.ToString() ?? "未知DB";
            ////////            string successStatus = s7r?.IsSuccess.ToString() ?? "未知状态";

            ////////            Logger.Info(LoggerType.Login,
            ////////                       $"写plcDB1000:db {dbInfo}-> {successStatus} {message}",
            ////////                       $"UserName:{UserContext.Current.UserName}",
            ////////                       null);
            ////////            //siemensS7Net.();//断开连接
            ////////            // 释放资源
            ////////            siemensS7Net = null;
            ////////        }
        }
        private bool TagFormSQL(string sN, string opName)
        {
            SiemensS7Net siemensS7Net = null;
            string message = string.Empty;
            bool isSuccess = false;
            mes_virtualrfidset2 tagSet = null;
            OperateResult s7r = null;

            try
            {
                //var opname = GetOP(sTag);
                var listB = _repository.DbContext.Set<MES_VirtualRFIDData>()
    .Where(b => b.SerialNumber == sN)
    .OrderByDescending(b => b.CreateDate) // 根据时间字段降序排序，假设时间字段为CreateTime
    .FirstOrDefault();

                if (listB == null)
                {
                    message = $"未找到OPName为{opName}的MES_VirtualRFIDData记录";
                    return false;
                }

                tagSet = _repository.DbContext.Set<mes_virtualrfidset2>()
                    .FirstOrDefault(b => b.OPName == opName);

                if (tagSet == null)
                {
                    message = $"未找到OPName为{opName}的MES_VirtualRFIDSet记录";
                    return false;
                }

                siemensS7Net = new SiemensS7Net(SiemensPLCS.S1200)
                {
                    IpAddress = tagSet.PlcIp,
                    Port = tagSet.PlcPort
                };

                var d = siemensS7Net.ConnectServer();

                if (!d.IsSuccess)
                {
                    //message = "PLC连接失败";
                    //return false;
                }

                byte[] bytes = new byte[100];
                s7r = siemensS7Net.Write(tagSet.DB, (byte[])bytes);
                isSuccess = s7r.IsSuccess;

                if (!isSuccess)
                {
                    message = s7r.Message ?? "PLC写入操作失败";
                }

                return isSuccess;
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return false;
            }
            finally
            {
                // 记录日志
                string dbInfo = tagSet?.DB?.ToString() ?? "未知DB";
                string successStatus = s7r?.IsSuccess.ToString() ?? "未知状态";

                Logger.Info(LoggerType.Login,
                           $"写plcDB1000:db {dbInfo}-> {successStatus} {message}",
                           $"UserName:{UserContext.Current.UserName}",
                           null);
                //siemensS7Net.();//断开连接
                // 释放资源
                siemensS7Net = null;
            }
        }
        private MES_ProductionPlanDetail GetUpDetail(string sN)
        {
           var t = _repository.DbContext.Set<MES_ProductionPlanDetail>()
                    .FirstOrDefault(b => b.MaterialCode == sN);
            return t;
        }
        /// <summary>
        /// 根据用户Id找对应的工位/工序编号
        /// </summary>
        /// <param name="sOp"></param>
        /// <returns></returns>
        private string GetOP(string sOp)
        {
            string rs = string.Empty;
            try
            {
                int userId = UserContext.Current.UserId;
                var listA = _repository.DbContext.Set<MES_UserPost>().FirstOrDefaultAsync(b => b.UserId == userId).Result;
                var listB = _repository.DbContext.Set<MES_Process>().FirstOrDefaultAsync(b => b.ProcessID.ToString() == listA.ProcessID).Result;
                rs = listB.ProcessName;
            }
            catch (Exception ex)
            {
            }
            return rs;
        }
    }
}
